package com.bai.ruiji.Controller;


import com.bai.ruiji.Common.R;
import com.bai.ruiji.Service.CategoryServer;
import com.bai.ruiji.pojo.Category;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 分类管理
 *
 * @author 27471
 * Time : 2022/10/10 13:26
 */
@RestController//返回JSON数据
@RequestMapping("/category")
@Slf4j
public class CategroyController {
    @Autowired
    private CategoryServer categoryServer;

    /**
     * 新增分类
     *
     * @param category
     * @return
     * @RequestBody 接收前端传给后端的JSON数据
     */
    @PostMapping
    public R<String> add(@RequestBody Category category) {
        categoryServer.save(category);
        return R.success("新增分类成功");
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @RequestMapping("/page")
    public R<Page> page(int page, int pageSize) {
        //分页构造器
        Page<Category> pageInfo = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //添加排序条件，根据sort进行排序
        queryWrapper.orderByAsc(Category::getSort);
        //进行分页查询
        categoryServer.page(pageInfo, queryWrapper);

        return R.success(pageInfo);
    }

    /**
     * 根据id删除分类
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(Long ids) {
        log.info("删除");
        categoryServer.rmove(ids);
        return R.success("分类信息删除成功");
    }

    /**
     * 根据id修改分类信息
     *
     * @param category
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Category category) {
        log.info("修改分类信息：{}", category);
        categoryServer.updateById(category);
        return R.success("修改分类信息成功");
    }

    /**
     * 根据条件查询分类数据
     *
     * @param category
     * @return
     */
    @RequestMapping("/list")
    public R<List<Category>> list(Category category) {
        //条件构造器
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //查询添加条件
        categoryLambdaQueryWrapper.eq(category.getType() != null, Category::getType, category.getType());
        //添加排序条件
        categoryLambdaQueryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getCreateTime);

        List<Category> list = categoryServer.list(categoryLambdaQueryWrapper);
        return R.success(list);
    }
}
